package com.guo.pet_store.admin.controller;

import com.guo.pet_store.admin.pojo.PetType;
import com.guo.pet_store.admin.service.TypeService;
import org.dom4j.rule.Mode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.lang.reflect.Type;

@Controller
@RequestMapping("/admin")
public class TypeController {
    @Autowired
    TypeService typeService;
    @GetMapping("/types")
    public String toTypes(Model model, Pageable pageable){
        model.addAttribute("page",typeService.listType(pageable));
        return "admin/types";
    }

    @GetMapping("/addType")
    public String getType(){
        return "admin/type-input";
    }
    @PostMapping("/addType")
    public String addType(PetType type, RedirectAttributes redirectAttributes){
        PetType petType = typeService.saveType(type);
        if (petType != null){
            redirectAttributes.addFlashAttribute("message","添加成功");
        }else {
            redirectAttributes.addFlashAttribute("message","添加失败");
        }
        return "redirect:/admin/types";
    }

    @GetMapping("/editType/{id}")
    public String getEditType(@PathVariable Long id,Model model){
        model.addAttribute("type",typeService.getAPetType(id));
        return "admin/type-input";
    }

    @PostMapping("/editType/{id}")
    public String editType(@PathVariable Long id, @RequestParam String name,RedirectAttributes redirectAttributes){
        typeService.editType(id,name);
        redirectAttributes.addFlashAttribute("message","修改成功!");
        return "redirect:/admin/types";
    }

//    {/admin/types/{id}/delete(id=${type.id}
    @GetMapping("/deleteType/{id}")
    public String deleteType(@PathVariable Long id,RedirectAttributes redirectAttributes){
        typeService.deleteType(id);
        redirectAttributes.addFlashAttribute("message","删除成功");
        return "redirect:/admin/types";
    }
}
